import 'package:flutter/material.dart';
import 'package:huajianshe_app/base/AppNavigator.dart';
import 'package:huajianshe_app/base/BaseState.dart';
import 'package:huajianshe_app/base/Refresher.dart';
import 'package:huajianshe_app/common/load_image.dart';
import 'package:huajianshe_app/common/res.dart';
import 'package:huajianshe_app/network/Api.dart';
import 'package:huajianshe_app/pages/main/CommentItem.dart';
import 'package:huajianshe_app/pages/main/model/CommentModel.dart';
import 'package:huajianshe_app/utils/Device.dart';
import 'package:huajianshe_app/utils/KeyboardUtil.dart';
import 'package:huajianshe_app/widget/SmartButton.dart';
import 'package:oktoast/oktoast.dart';

class LessonCommentPage extends StatefulWidget {

  final String? lessonSn;

  const LessonCommentPage(this.lessonSn, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _LessonCommentPageState();
  }
}

class _LessonCommentPageState extends BaseState<LessonCommentPage> {

  bool keyboardShown = false;
  bool showButton = false;
  TextEditingController editingController = TextEditingController();
  FocusNode inputNode = FocusNode();
  CommentListDataWithPageInfo? dataWithPageInfo;
  int page = 1;

  @override
  void initState() {
    super.initState();
    refresher = Refresher<CommentListData>(this);
    load(false);
  }

  void load(bool doNotShowProgressBar) {
    var data = {
      'page': page,
      'list_rows': 10,
      'aim_id': widget.lessonSn,
      'aim_type': 3 //1动态，3课程
    };
    sendReq(Api.commentList(), CommentListResp(), data: data, doNotShowProgressBar: doNotShowProgressBar);
  }

  @override
  void onRefresh() {
    super.onRefresh();
    refresher?.mode = Mode.refresh;
    page = 1;
    load(true);
  }

  @override
  void onLoadMore() {
    super.onLoadMore();
    refresher?.mode = Mode.loadMore;
    load(true);
  }

  @override
  void onReqSuccess<T>(T t, int code, String msg, String path) {
    super.onReqSuccess(t, code, msg, path);
    if (t is CommentListResp) {
      dataWithPageInfo = t.data;
      List<CommentListData>? data = dataWithPageInfo?.data;
      refresher?.load(data);
      setState(() { });
      page++;
    } else if (t is CommentResp) {
      showToast(t.msg ?? '');
      refresher?.insert2First(t.data);
      editingController.text = '';
      setState(() => null);
    }
  }

  void doComment(String? text) {
    if (text?.isNotEmpty == true) {
      var data = {
        'aim_type': 3,
        'aim_id': widget.lessonSn,
        'content': text
      };
      sendReq(Api.doComment(), CommentResp(), data: data, doNotShowProgressBar: false);
    }
  }

  @override
  Widget build(BuildContext context) {
    keyboardShown = KeyboardUtil.isKeyboardShown(context);
    // if (!keyboardShown) showButton = false;
    return
      Scaffold(
          backgroundColor: Colors.transparent,
          body:
          Container(
            child: Column(children: [
              SizedBox(height: 45, child: Row(children: [
                W(15),
                Text('评论 (共${dataWithPageInfo?.total ?? 0}条)', style: TS(15, C.gray1A)),
                Spacer(),
                SmartButton(width: 20, height: 20, drawableLeft: LoadImage('ic_close'), backgroundColor: Colors.transparent, borderColor: Colors.transparent,
                    onPressed: () { AppNavigator.pop(context); }),
                W(15)
              ])),
              D(),
              Expanded(child: refresher!.build(buildChild())),
              // if (showButton)
              buildBottom()
            ]),
          )

      );

  }

  Widget buildChild() {
    Widget? child = buildEmptyPage();
    if (child != null) {
      return child;
    }
    return
      ListView.separated(
          itemBuilder: (_, index) {
            return Padding(padding: EdgeInsets.all(15), child: CommentItem(refresher?.data?[index], null)); // 评论列表里进去的都是好友
          },
          separatorBuilder: (_, index) {
            return PD(1, 63, 0);
          },
          itemCount: (refresher?.data?.length ?? 0)
      );
  }

  Widget buildBottom() {
    return Container(color: C.grayF6, padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10), child: Row(
      mainAxisSize: MainAxisSize.max,
      children: [
        Expanded(child: TextField(
          autofocus: false,
          controller: editingController,
          focusNode: inputNode,
          textInputAction: TextInputAction.send,
          onSubmitted: (value) {
            print('submit $value');
            doComment(value);
          },
          decoration: InputDecoration(
              isDense: true,
              contentPadding: EdgeInsets.only(
                  left: 10, right: 10, top: 5, bottom: 5),
              fillColor: Colors.white,
              filled: true,
              border: new OutlineInputBorder(
                borderSide: BorderSide.none,
                borderRadius: const BorderRadius.all(
                  const Radius.circular(3.0),
                ),
              ),
              hintStyle: TextStyle(color: Color(0xffcccccc)),
              hintText: "说点什么吧"),
        )),
        if (keyboardShown && Device.isIOS)
          GestureDetector(onTap: () {FocusScope.of(context).unfocus();}, child: Icon(Icons.arrow_drop_down)),
        // TextButton(onPressed: null, child: Text('发布'))
      ],
    ),);
  }

  void onComment() {
    FocusScope.of(context).requestFocus(inputNode);
  }
}